package com.titleevaluation.service;

import com.titleevaluation.entity.Application;
import com.titleevaluation.entity.SocialInsuranceProof;
import com.titleevaluation.repository.ApplicationRepository;
import com.titleevaluation.repository.SocialInsuranceProofRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class SocialInsuranceProofService {

    private final SocialInsuranceProofRepository socialInsuranceProofRepository;
    private final ApplicationRepository applicationRepository;

    public SocialInsuranceProofService(SocialInsuranceProofRepository socialInsuranceProofRepository, ApplicationRepository applicationRepository) {
        this.socialInsuranceProofRepository = socialInsuranceProofRepository;
        this.applicationRepository = applicationRepository;
    }

    public SocialInsuranceProof createSocialInsuranceProof(Long applicationId, SocialInsuranceProof socialInsuranceProof) {
        Application application = applicationRepository.findById(applicationId)
                .orElseThrow(() -> new RuntimeException("Application not found"));
        socialInsuranceProof.setApplication(application);
        socialInsuranceProof.setCreatedAt(LocalDateTime.now());
        socialInsuranceProof.setUpdatedAt(LocalDateTime.now());
        return socialInsuranceProofRepository.save(socialInsuranceProof);
    }

    public List<SocialInsuranceProof> getSocialInsuranceProofByApplicationId(Long applicationId) {
        return socialInsuranceProofRepository.findByApplicationId(applicationId);
    }

    public Optional<SocialInsuranceProof> getSocialInsuranceProofById(Long id) {
        return socialInsuranceProofRepository.findById(id);
    }

    public SocialInsuranceProof updateSocialInsuranceProof(Long id, SocialInsuranceProof updatedSocialInsuranceProof) {
        SocialInsuranceProof existingSocialInsuranceProof = socialInsuranceProofRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("SocialInsuranceProof not found"));

        existingSocialInsuranceProof.setInsuranceUnit(updatedSocialInsuranceProof.getInsuranceUnit());
        existingSocialInsuranceProof.setVerificationStatus(updatedSocialInsuranceProof.getVerificationStatus());
        existingSocialInsuranceProof.setUpdatedAt(LocalDateTime.now());

        return socialInsuranceProofRepository.save(existingSocialInsuranceProof);
    }

    public void deleteSocialInsuranceProof(Long id) {
        socialInsuranceProofRepository.deleteById(id);
    }
}

